package com.dailyblue.example.project.bookstore.user.controller;

import com.dailyblue.example.project.bookstore.commons.bean.User;
import com.dailyblue.example.project.bookstore.commons.util.JsonResult;
import com.dailyblue.example.project.bookstore.commons.util.ResultTool;
import com.dailyblue.example.project.bookstore.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService service;

    @PostMapping("/login")
    public JsonResult login(User user) {
        return service.login(user);
    }

    @GetMapping("/check")
    public JsonResult check(HttpServletRequest request) {
        Object username = request.getSession().getAttribute("USER_NAME");
        Object size = request.getSession().getAttribute("SHOPPING_CART_SIZE");
        request.getSession().removeAttribute("USER_NAME");
        request.getSession().removeAttribute("SHOPPING_CART_SIZE");
        return ResultTool.success(username + "." + size);
    }

    @GetMapping("/logout")
    public JsonResult logout(HttpServletRequest request) {
        return service.logout(request.getHeader("token"));
    }

    @PostMapping
    public JsonResult register(@RequestBody User user) {
        log.info("user:{}", user);
        return service.register(user);
    }

    @PostMapping("/add_cart/{bookId}")
    public JsonResult addCart(@PathVariable String bookId, HttpServletRequest request) {
        return service.addCart(bookId, request);
    }

    @GetMapping("/show_cart")
    public JsonResult showCart(HttpServletRequest request) {
        return service.showCart(request);
    }

    @PutMapping("/change_cart/{bookId}/{number}")
    public JsonResult changeCartNumber(@PathVariable String bookId, HttpServletRequest request, @PathVariable int number) {
        return service.changeCartNumber(bookId, request, number);
    }

    @PutMapping("/change_cart2/{bookId}/{number}")
    public JsonResult changeCartNumber2(@PathVariable String bookId, HttpServletRequest request, @PathVariable int number) {
        return service.changeCartNumber2(bookId, request, number);
    }

    @DeleteMapping("/delete_cart")
    public JsonResult deleteCartById(HttpServletRequest request, String... bookIds) {
        return service.deleteCartById(request,bookIds);
    }
}
